using System;
using System.Collections.Generic;
using System.Text;
using Castle.DynamicProxy;
using Sio.Mdm.Utils;
using System.Reflection;
using Castle.Core.Interceptor;

namespace Sio.Mdm.Server
{
    static class Logging
    {
        #region Methods

        #region Internal

        #region WriteEnterCall
        internal static void WriteEnterCall(IInvocation invocation, object[] args)
        {
            Logger.WriteDebug("Entering function {0}", invocation.Method.Name);
            LogParameters(invocation.Method, args);
        }
        #endregion

        #region WriteLeaveCall
        internal static void WriteLeaveCall(IInvocation invocation, object retVal, object[] args)
        {
            Logger.WriteDebug("Leaving function {0}", invocation.Method.Name);
            LogParameters(invocation.Method, args);

            if (retVal == null)
            {
                if (invocation.Method.ReturnType == typeof(void))
                {
                    Logger.WriteDebug("Return value: <void>");
                }
                else
                {
                    Logger.WriteDebug("Return value: <null>");
                }
            }
            else
            {
                Logger.WriteDebug("Return value: {0}", retVal);
            }
        } 
        #endregion

        #region WriteSecurityLog
        internal static void WriteSecurityLog(IInvocation invocation)
        {   
        } 
        #endregion

        #endregion

        #region Private

        #region LogParameters
        private static void LogParameters(MethodInfo method, object[] args)
        {
            ParameterInfo[] fields = method.GetParameters();

            for (int i = 0; i < fields.Length; i++)
            {
                LogParameter(fields[i], args[i]);
            }
        } 
        #endregion

        #region LogParameter
        private static void LogParameter(ParameterInfo param, object value)
        {
            if (value == null)
            {
                Logger.WriteDebug("{0} {1} = <null>", param.ParameterType.Name, param.Name);
            }
            else
            {
                Logger.WriteDebug("{0} {1} = {2}", param.ParameterType.Name, param.Name, value.ToString());
            }
        }  
        #endregion

        #endregion

        #endregion
    }
}
